package cn.tansanqinger.agency;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

class Message{
    public void send(String str){
        System.out.println("消息发送："+str);
    }
}
class MessageProxy implements MethodInterceptor {
    Object object;
    public MessageProxy(Object object) {
        this.object = object;
    }
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object returnObject = null;
        if(this.connect()){
            returnObject = method.invoke(this.object,args);
            this.close();
        }
        return returnObject;
    }
    public boolean connect(){
        System.out.println("发送消息通道打开……");
        return true;
    }
    public void close(){
        System.out.println("关闭消息发送通道……");
    }
}
public class CGLIBDemo {
    public static void main(String[] args) {
        Message realObject = new Message();//真实业务主题对象
        Enhancer enhancer = new Enhancer();//负责代理控制的类
        enhancer.setSuperclass(realObject.getClass());//模拟一个操作的父类
        enhancer.setCallback(new MessageProxy(realObject));//设置代理对象
        Message proxyObject = (Message) enhancer.create();//创建代理对象，类似于Proxy
        proxyObject.send("www.tansanqinger.cn");
    }
}
